package com.lcf.app.redis.config;

import com.lcf.app.redis.model.CacheConstant;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author ChenFei
 * @date 2021/11/1
 */
@Configuration
public class RedisCacheConfig extends CachingConfigurerSupport {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofDays(31)) // 设置缓存的默认过期时间
                .disableCachingNullValues(); // 不缓存空值

        //设置cacheNames
        Set<String> cacheNames = new HashSet<>();
        cacheNames.add(CacheConstant.USER_CACHE);

        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put(CacheConstant.USER_CACHE, config.entryTtl(Duration.ofMinutes(1)));//设置缓存过期时间


        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .initialCacheNames(cacheNames)
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }
}
